Skip to content

optimising the factors such as resizing and copying#21

Open
Butcher3Years wants to merge 1 commit intoDynamic-arraysfrom
Optimising-usage----(std-vector)
Open

optimising the factors such as resizing and copying#21
Butcher3Years wants to merge 1 commit intoDynamic-arraysfrom
Optimising-usage----(std-vector)

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

Optimizing std::vector – reserve, emplace_back, resizing & copying pain 🪓

Branch: vector-optimizations
From The Cherno's C++ series — the episodes where he screams about people killing performance with naive push_back loops.

Core Problem: Reallocation & Copying

std::vector grows dynamically. When size() reaches capacity(), it:

  • Allocates new bigger block (usually 1.5×–2× old capacity)
  • Copies/moves all existing elements to new memory
  • Deletes old block

This is expensive — especially with large or complex types (deep copies, many reallocations).

Cherno:

"If you keep pushing without reserve, you're copying the whole vector over and over.
That's not O(n) — it's O(n²) in the worst case. Don't be that guy."

Key Optimizations

  1. reserve(n) – Pre-allocate capacity

    std::vector<int> v;
    v.reserve(1'000'000);             // one big allocation
    
    for (int i = 0; i < 1'000'000; ++i) {
        v.push_back(i);               // no reallocations, no copies
    }
    
    
    

reserve only allocates memory — does not change size()

emplace_back-Construct in-place (no copy/move)

std::vectorstd::string names;

// BAD – creates temporary string → copies/moves into vector
names.push_back("Cherno");

// GOOD – constructs string directly inside vector's memory
names.emplace_back("Cherno");

// Even better – forward arguments
names.emplace_back(10, 'a'); // "aaaaaaaaaa" – no temporary

push_back → creates temporary → copy/move into vector
emplace_back → perfect forwarding → constructs directly → no extra objects

Avoid unnecessary copies when copying vectors

std::vector src(1000);

// BAD – deep copies 1000 objects
std::vector dst = src;

// BETTER – pre-reserve + bulk insert
std::vector dst;
dst.reserve(src.size());
dst.insert(dst.end(), src.begin(), src.end());

// BEST – if you can steal: use std::move
std::vector dst = std::move(src); // src now empty

RuleWhy It Saves Your AssAlways reserve(n) before known-size loopAvoids reallocations & copiesPrefer emplace_back over push_backNo temporaries, no copy/moveUse reserve + insert for bulk copyMuch faster than copy ctor loopstd::move when you can steal resourcesAvoid deep copiesKnow capacity() vs size()Reallocation = performance killerUse shrink_to_fit() after massive eraseRelease unused capacity (optional)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant